package com.etoak.controller;

import com.etoak.commons.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

    @Value("${image.dir}")
    String  uploadDir;


    @Value("${image.path}")
    String  pathPrefix;

    public static final String  JPG = "image/jpeg";
    public static final String  PNG = "image/png";


        @PostMapping("/upload")
    public ResultVO  upload(MultipartFile file){
    //文件!null
        if (ObjectUtils.isEmpty(file)||file.getSize()<= 0){
            return ResultVO.error("文件不能为空");
        }

        //文件类型
         String contentType = file.getContentType();
        if (!StringUtils.equalsAnyIgnoreCase(contentType,PNG,JPG)){
            return  ResultVO.error("仅支持JPG/PNG格式");
        }
        //修改文件名称
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newFilename = StringUtils.join(uuid,".",extension);
        //目标文件夹
            File   destDir = new File(this.uploadDir);
            if (!destDir.exists()){
                destDir.mkdirs();
            }
            //
            File destFile = new File(destDir,newFilename);


            //
            try {
                file.transferTo(destFile);
            } catch (IOException e) {
              log.error(e.getMessage(),e);
              return  ResultVO.error("图片上传失败");
            }
            //图片访问
            String  path = pathPrefix.endsWith("/") ?
                    StringUtils.join(pathPrefix + newFilename)  :
                    StringUtils.join(pathPrefix,"/",newFilename);

            return  ResultVO.success(path);

        }

}
